<template>
    <div id="indexMap-map" style="width:100%;height:680px;"></div>
  </template>
  <script>
  import '@/assets/map/ol/ol.css';
  import { getProjection } from "@/map/projMap.js";
  import Map from 'ol/Map';
  import View from 'ol/View';
  import VectorLayer from 'ol/layer/Vector';
  import {Vector as VectorSource} from 'ol/source';
  import WKT from 'ol/format/WKT';
  import {boundingExtent} from 'ol/extent';
  import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
  import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';
  import redMarkerSmall from '@/assets/map/image/newImage/redMarkerSmall.png';
  import blueMarkerSmall from '@/assets/map/image/newImage/blueMarkerSmall.png';
  
  export default {
    name: "IndexMap",
    components: {
  
    },
    props:{
  
    },
    emits:["getMap"],
    data() {
      return {
        str: "indexMap",
        map: null,
        // center: [105, 34],
        // zoom: 4,
        center: [105, 27.5],
        zoom: 4,
        //活动点
        allActivityDataList:[],//全部活动点数据列表
        allActivityPointLayer:null,//活动点图层
      }
    },
    watch: {
  
    },
    created() {
  
    },
    mounted() {
      console.log("mounted");
      let that = this;
      //地图异步加载
      this.$nextTick(function(){
        console.log('地图异步加载');
        //地图异步加载
        setTimeout(() => {
          //初始化地图信息
          that.initMap();
          //获取全部活动点数据列表
          that.getAllActivityDataList();
          //显示全部活动点图层
          that.showAllActivityPointLayer();
        }, 200);
      });
    },
    beforeCreate() {//生命周期创建之前
      console.log("beforeCreate");
    },
    beforeMount() {//生命周期挂载之前
      console.log("beforeMount");
    },
    beforeUpdate() {//生命周期更新之前
      console.log("beforeUpdate");
    },
    updated() {//生命周期更新之后
      console.log("updated");
    },
    beforeDestroy() {//生命周期销毁之前
      console.log("beforeDestroy");
    },
    destroyed() {//生命周期销毁完成
      this.map = null;
      console.log("销毁地图");
    },
    activated() {//如果页面有keep-alive缓存功能激活，这个函数会触发
      console.log("activated-"+this.str);
      //自动获取地图div高度
      this.autodivheight();
      //浏览器窗口发生变化时同时变化DIV高度
      window.onresize=this.autodivheight;
    },
    deactivated() {//如果页面有keep-alive缓存功能停用，这个函数会触发
      console.log("deactivated-"+this.str);
      //取消浏览器窗口发生变化时同时变化DIV高度事件
      window.onresize = null;
    },
    methods: {
      initMap() {
        // debugger;
        let that = this;
        let mapStr = this.str;
        let targetMap = document.getElementById(mapStr+"-map");
        if(targetMap.innerHTML!=""){
          console.log("清空targetMap");
        }
        targetMap.innerHTML = "";//清空
        //自动获取地图div高度
        this.autodivheight();
        //浏览器窗口发生变化时同时变化DIV高度
        window.onresize=this.autodivheight;
        if(this.map){//避免重复加载地图
          console.log("避免重复加载地图");
          return;
        }
        console.log("初始化地图");
        //获取投影4490坐标系
        this.projection4490 = getProjection();
        //初始化地图信息
        this.map = new Map({
          target: targetMap.id,
          /*controls: defaultControls({attributionOptions: {collapsed: false}})
              .extend([new Logo()]),*/
          view: new View({
            center: this.center,
            maxZoom: 18,
            minZoom: 3,
            zoom: this.zoom,
            constrainResolution:true,//缩放地图可移动到最近的缩放级别（整数zoom级别）
            projection: 'EPSG:4490',
            // resolutions:getResolutions()
          })
        });
        console.log("this.map");
        console.log(this.map);
  
        //活动点图层
        this.allActivityPointLayer = new VectorLayer({
          source: new VectorSource({
            wrapX: false
          }),
          projection: 'EPSG:4490'
        });
        this.map.addLayer(this.allActivityPointLayer);
        this.allActivityPointLayer.setZIndex(9);
  
        //弹出窗口
        let popupTarget = document.getElementById(this.str+"-popup");
        if(popupTarget){
          this.popupInfoLayer = new Overlay({
            element: popupTarget,
            positioning: 'center-center'
          });
          this.map.addOverlay(this.popupInfoLayer);
          //显示弹出窗口
          document.getElementById(this.str+"-popup").style.display="block";
          //关闭弹出事件
          document.getElementById(this.str+"-popup-closer").onclick = function () {
            that.popupInfoLayer.setPosition(undefined);
            //隐藏弹出窗口
            document.getElementById(that.str+"-popup").style.display="none";
          };
        }
  
        //地图对象传递
        this.$emit("getMap",this.map);
      },
      autodivheight() {//自动获取div高度
        //获取浏览器窗口高度
        let winHeight = 0;
        if (window.innerHeight) {
          winHeight = window.innerHeight;
        } else if ((document.body) && (document.body.clientHeight)) {
          winHeight = document.body.clientHeight;
        }
        //通过深入Document内部对body进行检测，获取浏览器窗口高度
        if (document.documentElement && document.documentElement.clientHeight) {
          winHeight = document.documentElement.clientHeight;
        }
        //全屏时窗口高度:864px,地图div高度:680px
        let tempHeight = 864;
        let mapTempHeight = 740;
        let mapHeight = winHeight - tempHeight + mapTempHeight;
        /*//最小高度
        if(mapHeight<480){
          mapHeight = 480;
        }*/
        //设置地图高度
        document.getElementById(this.str+"-map").style.height= mapHeight +"px";
        console.log("窗口高度："+winHeight+"地图高度："+mapHeight);
        //resize事件--刷新地图,确保地图不变形
        if(this.map){
          this.map.updateSize();
          console.log("resize事件--刷新地图,确保地图不变形");
        }
      },
      getPointStyle(){// 点图标样式
        let style = new Style({
          image: new Icon({
            src: dingweiImg,
            anchor: [0.5, 1]
          }),
        });
        return style;
      },
      getActivityPointStyle(type){//活动点图标样式
        let style = new Style({
          image: new Icon({
            src: dingweiImg,
            anchor: [0.5, 1]
          }),
        });
        if(type=="red"){
          style = new Style({
            image: new Icon({
              src: redMarkerSmall,
              scale:1,
            }),
          });
        }else if(type=="blue"){
          style = new Style({
            image: new Icon({
              src: blueMarkerSmall,
              scale:1,
            }),
          });
        }
        return style;
      },
      getLineStringStyle(color,fillColor,width){//线样式
        if(fillColor!=null){
          //填充样式
        }else{
          fillColor = "rgba(0,0,0,0)";
        }
        if(width!=null){
          //线宽度
        }else{
          width = 2;
        }
        let style = new Style({
          fill:new Fill({//填充样式
            color:fillColor
          }),
          stroke:new Stroke({//描绘
            width:width,//宽
            color:color
          }),
          zIndex: 100
        });
        return style;
      },
      getPolyonStyle(color,fillColor,width){//多边形样式
        if(fillColor!=null){
          //填充样式
        }else{
          fillColor = "rgba(0,0,0,0)";
        }
        if(width!=null){
          //线宽度
        }else{
          width = 2;
        }
        let style = new Style({
          fill:new Fill({//填充样式
            color:fillColor
          }),
          stroke:new Stroke({//描绘
            width:width,//宽
            color:color
          }),
          zIndex: 100
        });
        return style;
      },
      getSelectPolyonStyle(){//选中要素样式
        let style = new Style({
          fill:new Fill({//填充样式
            color:"rgba(255,255,255,0.2)"
          }),
          stroke:new Stroke({//描绘
            width:2,//宽
            color:"rgba(30,144,255,1)"
          })
        });
        return style;
      },
      showBoundingExtent(coordinates){//缩放到区域位置
        console.log("缩放到区域位置");
        if (coordinates!=null && coordinates.length > 1) {
          const extent = boundingExtent(coordinates);
          //this.map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
          this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
          //获取默认位置
          this.center = this.map.getView().getCenter();
          this.zoom = this.map.getView().getZoom();
        }
      },
      //获取全部活动点数据列表
      getAllActivityDataList(){
        this.allActivityDataList = [
          {name:"人民大会堂",geom:"POINT(116.38746429314783 39.903761441695686)"},
        ];
      },
      //显示全部活动点图层
      showAllActivityPointLayer(){
        if(this.allActivityPointLayer!=null){
          this.allActivityPointLayer.getSource().clear();//清空
          let list = this.allActivityDataList;
          if(list!=null && list.length>0){
            for(let i=0;i<list.length;i++){
              let type = "1";//国家级
              let style = this.getActivityPointStyle("blue");//国家级图标样式
              if(i%2==0){//test
                type = "2";//省级
                style = this.getActivityPointStyle("red");//省级图标样式
              }
              let name = list[i].name;
              let geomText = list[i].geom;
              if(geomText!=null && geomText!=""){
                //空间数据
                let featureTmp = new WKT().readFeature(geomText);
                //设置属性
                featureTmp.setProperties({
                  name:name,//名称
                  type:type,//1国家级2省级
                });
                featureTmp.setStyle(style);
                //添加矢量数据
                this.allActivityPointLayer.getSource().addFeature(featureTmp);
              }
            }
          }
        }
      },
    }
  }
  
  </script>
  
  <style lang="scss" scoped>
  
  </style>